<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Strings in Ruby</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Ruby, strings, programming, language, learn Ruby">
<meta name="description" content="In this part of the Ruby tutorial, we cover Ruby strings.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Strings in Ruby</h1>

<p>
In this part of the Ruby tutorial, we will work with string 
data in more detail.  
</p>

<p>
Strings are one of the most important data types in computer languages. 
That is why we dedicate a whole chapter to working with strings in Ruby. 
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<p>
A string is a sequence of unicode characters. It is a data type which stores a 
sequence of data values in which elements usually stand for characters according 
to a character encoding. When a string appears literally in source code, 
it is known as a <b>string literal</b>.
</p>


<h2>First example</h2>

<p>
In Ruby string literals are enclosed by single or double quotes. 
</p>


<pre class="code">
#!/usr/bin/ruby

# first.rb

puts 'Python language'
puts "Ruby language"
</pre>

<p>
The example has two string literals. The first one is enclosed in
single qoutes. The other one is enclosed in double quotes. 
</p>

<pre>
$ ./first.rb 
Python language
Ruby language
</pre>

<p>
Output. 
</p>


<h2>Using quotes</h2>

<p>
What if we wanted to display quotes, for example in a direct speech?
There are basically two ways to do this. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "There are many stars" 
puts "He said, \"Which one is your favourite?\""

puts 'There are many stars'
puts 'He said, "Which one is your favourite?"'
</pre>

<p>
We use the (\) character to escape additional quotes. Normally the double quote
character is used to delimit a string literal. However, when escaped, the original 
meaning is supressed. It appears as a normal character and can be used withing a string
literal. The second way to use quotes within quotes is to mix single and double quotes. 
</p>

<pre>
$ ./quotes.exe 
There are many stars.
He said, "Which one is your favourite?"
</pre>

<p>
Output. 
</p>

<h2>Escape sequences</h2>

<p>
Escape sequences are special characters, that have a specific meaning, 
when used within a string literal.
</p>

<pre class="code">
#!/usr/bin/ruby

puts "one two three four"
puts "one\ntwo\nthree\nfour"
</pre>

<p>
One of the most common escape sequences is the newline character \n.
It is available in many programming languages. The next character after
the newline will appear on the new line. 
</p>

<pre>
$ ./newline.rb
one two three four
one
two
three
four
</pre>

<p>
Words after newline characters appear on new lines in the output
of the about script. 
</p>

<hr class="btm">

<p>
The r, b and t characters are normal alpabetical characters. When preceded
with a \ character, they have a special meaning. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "   bbb\raaa" 
puts "Joan\b\b\bane" 
puts "Towering\tinferno" 
</pre>

<p>
In the above example, we use three different escape characters. 
</p>

<pre class="explanation">
puts "   bbb\raaa"
</pre>

<p>
The carriage return \r is a control character for end of line 
return to beginning of line. Before the string is printed to the console,
it is first processed. The escape sequence causes the aaa characters to be
placed before the bbb characters. The output is aaabbb.
</p>

<pre class="explanation">
puts "Joan\b\b\bane" 
</pre>

<p>
The \b control character is a backspace. It deletes a preceding character. 
The string printed to the console is 'Jane' not 'Joan'. 
</p>

<pre class="explanation">
puts "Towering\tinferno" 
</pre>

<p>
Finally, the \t escape sequence places a tab space between the two
words. 
</p>

<pre>
$ ./escapes.rb 
aaabbb
Jane
Towering        inferno
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
The backslash character \ is a special character used to create escape 
sequences. When there is a need to print a backslash itself, it is preceded
with another backslash. Its default meaning is escaped and it is printed. 
The single and double quotes are used to delimit strings in Ruby. In order
to print them, they are preceded by \ too. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "The special character \\"
puts "The special character \'"
puts "The special character \""
</pre>

<p>
In this simple script, we print all three characters to the terminal. 
</p>

<pre>
$ ./specials.rb
The special character \
The special character '
The special character "
</pre>

<p>
Output. 
</p>

<h2>Accessing string elements</h2>

<p>
It is possible to access string elements in Ruby. For this we use the
square brackets []. Inside the brackets, we can put strings, indexes or
ranges.  
</p>

<pre class="code">
#!/usr/bin/ruby

msg = "Ruby language"

puts msg["Ruby"]
puts msg["Python"]

puts msg[0]
puts msg[-1]

puts msg[0, 3]
puts msg[0..9]
puts msg[0, msg.length]
</pre>

<p>
This code example shows, how we can access parts of a string. 
</p>

<pre class="explanation">
msg = "Ruby language"
</pre>

<p>
Here is the string, that we will be accessing. 
</p>

<pre class="explanation">
puts msg["Ruby"]
</pre>

<p>
In this code line we test, whether string 'Ruby' is a substring
of the msg string. If it is true, then the string that we are looking
for is returned. 
</p>

<pre class="explanation">
puts msg[0]
</pre>

<p>
The characters of the string can be accessed by their index. The numbers
start from 0. In other words, the 0 is the index of the first character. 
The msg[0] returns the first character of the string, namely R.
</p>

<pre class="explanation">
puts msg[-1]
</pre>

<p>
Here we access the last character of the string. The -1 stands for the last
index of the string. 
</p>

<pre class="explanation">
puts msg[0, 3]
</pre>

<p>
Two indexes separated by a comma return characters starting from the first
index and ending with the second index, excluded. 
</p>

<pre class="explanation">
puts msg[0..9]
</pre>

<p>
A range operator can be used as well. Here we print
the first ten characters of the msg string.
</p>

<pre class="explanation">
puts msg[0, msg.length]
</pre>

<p>
This line returns the whole string. The msg.length returns the
size of the string.
</p>

<pre>
$ ./access.rb
Ruby

R
e
Rub
Ruby langu
Ruby language
</pre>

<p>
Output of the example. 
</p>

<h2>Multiline strings</h2>

<p>
In many programming languages creating multiline strings
requires additional effort. Escpecially in Visual Basic. In Ruby,
multiline strings are created easily. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "I hear Mariachi static on my radio 
And the tubes they glow in the dark 
And I'm there with her in Ensenada 
And I'm here in Echo Park
"

puts %/
Carmelita hold me tighter
I think I'm sinking down 
And I'm all strung out on heroin
On the outskirts of town/

puts &lt;&lt;STRING

Well, I'm sittin' here playing solitaire
With my pearl-handled deck 
The county won't give me no more methadone 
And they cut off your welfare check
STRING
</pre>

<p>
In the example, we have lyrics of a Carmelita song. 
We show three ways to print multiline strings. They can 
be used within double quotes. We can use a % character to 
build a multiline string. The character following the % also
encloses the string. Finally, we can use the heredoc syntax. 
In this syntax, we use &lt;&lt; followed by some string. 
The string encloses the multiline strings. It must also be
left aligned.  
</p>


<h2>Variable interpolation</h2>

<p>
Variable interpolation is replacing variables with their values inside string literals. 
To substitute a variable with a value, the variable name is put between #{ and } characters
inside the string literal.
</p>

<pre class="code">
#!/usr/bin/ruby

name = "Jane"
age = 17

puts "#{name} is #{age} years old"
</pre>

<p>
In this example, we subsitute two variables in the string. The name
and the age. 
</p>

<pre>
$ ./interpolation.rb 
Jane is 17 years old
</pre>

<hr class="btm">

<p>
In the substitution it is possible to use expressions. 
</p>

<pre class="code">
#!/usr/bin/ruby

x = 5
y = 6

puts "The product of #{x} and #{y} is #{x*y}"
</pre>

<p>
This is an example of the expression in the substitution.
</p>

<pre>
$ ./interpolation2.rb
The product of 5 and 6 is 30
</pre>

<p>
Running the example.
</p>


<hr class="btm">

<p>
There is another way to substitute variables in a string. It is similar
to how interpolation is done in Python langugage. 
</p>

<pre class="code">
#!/usr/bin/ruby

name = "Jane"
age = 17

message = "%s is %d years old" % [name, age]
puts message
</pre>

<p>
Example. 
</p>

<pre class="explanation">
message = "%s is %d years old" % [name, age]
</pre>

<p>
We build a string before we use it. The %s and %d are formatting characters
that expect a string and a number, respectively. The values are provided in 
square brackets after the % character. 
</p>

<h2>Concatenating strings</h2>

<p>
Concatenating strings is creating one string from multiple strings. 
</p>

<pre class="code">
#!/usr/bin/ruby

lang = "Ruby" + " programming" + " languge"
puts lang

lang = "Python" " programming" " language"
puts lang

lang = "Perl" &lt;&lt; " programming" &lt;&lt; " language"
puts lang

lang = "Java".concat(" programming").concat(" language")
puts lang
</pre>

<p>
In Ruby, there are multiple ways, how we can concatenate strings. 
</p>

<pre class="explanation">
lang = "Ruby" + " programming" + " languge"
</pre>

<p>
The plus operator is the most common operator used to add strings in
computer languages. Perl and PHP use the dot (.) operator to concatenate
strings. 
</p>

<pre class="explanation">
lang = "Python" " programming" " language"
</pre>

<p>
Ruby automatically concatenates subsequent strings.
</p>

<pre class="explanation">
lang = "Perl" &lt;&lt; " programming" &lt;&lt; " language"
</pre>

<p>
Another operator which can be used to concatenate strings is &lt;&lt;.
</p>

<pre class="explanation">
lang = "Java".concat(" programming").concat(" language")
</pre>

<p>
Each string literal is in fact an object. We can call various methods
on each Ruby object. On string objects, we can call the <code>concat</code>
method, which adds two string objects. It also returns the final object, on
which we can call another method. So we can place these methods in a chain.
</p>

<pre>
$ ./concatenate.rb
Ruby programming languge
Python programming language
Perl programming language
Java programming language
</pre>

<p>
Output. 
</p>

<h2>Freezing strings</h2>

<p>
In Java or C#, the strings are immutable. This means, that we cannot modify
an existing string. We can only create a new string out of an existing one.
In Ruby, the strings are not immutable by default.
</p>

<p>
String objects in Ruby have a <code>freeze</code> method, which makes
them immutable. 
</p>

<pre class="code">
#!/usr/bin/ruby

msg = "Jane"
msg &lt;&lt; " is " 
msg &lt;&lt; "17 years old"

puts msg

msg.freeze

#msg &lt;&lt; "and she is pretty"
</pre>

<p>
In this example, we demonstrate, that the strings can be modified, if
needed. However, after calling the freeze method on a string object,
we cannot modify the string anymore. If we uncomment the code line,
we will get 'can't modify frozen string' error message. 
</p>


<h2>Comparing strings</h2>

<p>
Comparing strings is a common job in programming. 
We can compare two strings with a == operator or with a
<code>eql?</code> method. They return true, if the strings 
are equal and false, if not. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "12" == "12"
puts "17" == "9"
puts "aa" == "ab"

puts "Jane".eql? "Jan"
puts "Jane".eql? "Jane"
</pre>

<p>
In this code example, we compare some strings. 
</p>

<pre class="explanation">
puts "12" == "12"
</pre>

<p>
These two strings are equal, the line returns true. 
</p>

<pre class="explanation">
puts "aa" == "ab"
</pre>

<p>
The first two characters of both strings are equal. Next the 
following characters are compared. They are different so the
line returns false. 
</p>

<pre class="explanation">
puts "Jane".eql? "Jan"
</pre>

<p>
The <code>eql?</code> method is used to compare two strings. Strings are
objects and all have a built-in <code>eql?</code> method. The method takes
one parameter, the string to which we are comparing our first string. 
</p>

<pre>
$ ./comparing.rb
true
false
false
false
true
</pre>

<p>
Output of the program. 
</p>

<hr class="btm">

<p>
Ruby has a <b>spaceship</b> operator &lt;==&gt;. The operator comes from the Perl language.
Unlike the above two ways of comparing strings, which return either true or false, this
operator will return 1, 0, or −1. Depending on the value of the left 
argument relative to the right argument. If the left argument is greater than the right 
argument, the operator returns 1. If the left argument is less than the right argument, 
the operator returns −1. If the two arguments are equal, the operator returns 0.
What does it mean that a character is greater than another character? Characters are 
ordered in tables. Each character has a position in a table. When comparing characters, 
we compare their positions in such a table. For example in a ASCII table, the character
a comes before the character b. So comparing a &lt;==&gt; b returns -1, because the left 
argument has a lower position than b. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "a" &lt;==&gt; "b"
puts "b" &lt;==&gt; "a"
puts "a" &lt;==&gt; "a"
</pre>

<p>
Comparing characters with a spaceship operator. 
</p>

<pre>
$ ./spaceship.rb
-1
1
0
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
In is possible to compare strings regardless of the case. For
this Ruby has a <code>casecmp</code> method. The method
works the same way as the spaceship operator. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "Jane".casecmp "Jane"
puts "Jane".casecmp "jane"
puts "Jane".casecmp "Jan"
</pre>

<p>
Example. 
</p>

<pre class="explanation">
puts "Jane".casecmp "Jane"
puts "Jane".casecmp "jane"
</pre>

<p>
These two lines return the same result, 0. In this case
we do not take into account whether the characters are in
upper or lower case. 
</p>

<pre>
$ ./case.rb
0
0
1
</pre>

<p>
Output of the example. 
</p>

<h2>Strings are objects</h2>

<p>
Ruby is an object-oriented language. Objects are basic building blocks of 
an OOP program. Strings are objects too. An object is a combination of 
data and methods. In a OOP program, objects are created and they communicate
among themselves. 
</p>


<pre class="code">
#!/usr/bin/ruby

website = "google.com"
puts website

website = String.new "zetcode.com"
puts website
</pre>

<p>
In the example above, we show two basic ways of creating a string in Ruby. 
</p>

<pre class="explanation">
website = "google.com"
</pre>

<p>
Here a string literal is assigned to a website variable. Under the hood, the
Ruby interpreter creates a string object.
</p>

<pre class="explanation">
website = String.new "zetcode.com"
</pre>

<p>
This is the standard way of creating string objects. However, the first
one is used in most cases. Because it is less verbose and it is the
common way of creating strings in most computer languages. 
</p>

<hr class="btm">

<pre class="code">
#!/usr/bin/ruby

puts "zetcode".upcase
puts "zetcode".size
puts "zetcode".reverse
</pre>

<p>
In this code example, we call three methods on a
string literal. For people who are familiar with Java, C and
similar languages, this may be cofusing. In Ruby, a string literal
is transfromed into a string object upon which it is possible to 
call methods. 
</p>

<pre>
$ ./stringobject2.rb
ZETCODE
7
edoctez
</pre>

<p>
Output of the example. 
</p>


<h2>String methods</h2>


<p>
Ruby string objects have useful methods that 
can be used for working with strings. We have 
already seen several string methods like <code>concat</code>
or <code>eql?</code>. 
</p>

<pre class="code">
#!/usr/bin/ruby

word = "Determination"

puts "The word #{word} has #{word.size} characters"

puts word.include? "tion"
puts word.include? "tic"

puts

puts word.empty?
word.clear
puts word.empty?
</pre>

<p>
We have a string variable. Four string methods are presented.
</p>

<pre class="explanation">
puts "The word #{word} has #{word.size} characters"
</pre>

<p>
The <code>size</code> method returns the number of characters in the
string.
</p>

<pre class="explanation">
puts word.include? "tion"
</pre>

<p>
The <code>include?</code> method determines, whether a substring
is present in the tested string. In this case, the code line
returns true. 
</p>

<pre class="explanation">
puts word.empty?
word.clear
</pre>

<p>
The <code>emtpy?</code> method checks, whether the string is empty.
It returns a boolean true or false. The <code>clear</code> method
makes string empty.
</p>

<pre>
$ ./basicmethods.rb
The word Determination has 13 characters
true
false

false
true
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
In the next example, we will have methods that work with the
case of the characters. 
</p>

<pre class="code">
#!/usr/bin/ruby

ruby = "Ruby programming language"

puts ruby.upcase
puts ruby.downcase
puts ruby.capitalize
puts ruby.swapcase
</pre>

<p>
Ruby has four methods for character case. The <code>upcase</code> method
returns a copy of the string in which all characters are in uppercase. 
The <code>downcase</code> method returns a copy of the string in which 
all characters are in downcase. The <code>capitalize</code> method returns a copy 
of string with the first character converted to uppercase and the remainder 
to lowercase. Finally, the <code>swapcase</code> method returns a copy of the string
where the uppercase letters are converted to downcase and vice versa. 
</p>

<pre>
$ ./rubylang.rb
RUBY PROGRAMMING LANGUAGE
ruby programming language
Ruby programming language
rUBY PROGRAMMING LANGUAGE
</pre>

<p>
Output. 
</p>


<hr class="btm">

<p>
Next we present two Ruby string methods. The <code>start_with?</code>
method and the <code>end_with?</code> method. Both methods return a 
boolean true or false. They determine, whether a string starts or
ends with a specific string, respectively. 
</p>

<pre class="code">
#!/usr/bin/ruby

ws1 = "zetcode.com"
ws2 = "www.gnome.org"

puts ws1.start_with? "www."
puts ws2.start_with? "www."

puts

puts ws1.end_with? ".com"
puts ws2.end_with? ".com"
</pre>

<p>
This is an example for the aforementioned methods. 
</p>

<pre class="explanation">
puts ws1.start_with? "www."
</pre>

<p>
Here we check, if a string starts with a "www." prefix. 
It does not, so the output to the console is a boolean false.
</p>

<pre class="explanation">
puts ws1.end_with? ".com"
</pre>

<p>
We check, whether the ws1 string variable ends with a ".com"
suffix. It does, so we see a true in the console. 
</p>

<pre>
$ ./startend.rb
false
true

true
false
</pre>

<p>
Output. 
</p>

<hr class="btm">

<p>
In the following example, we will deal with the <code>inspect</code> method.
The method returns a raw string, surrounded by quote marks,
with special characters not interpreted. It is useful when we want
to examine what characters form the string. 
</p>

<pre class="code">
#!/usr/bin/ruby

msg = "Jane\t17\nThomas\t23"

puts msg
puts msg.inspect
</pre>

<p>
An example of the <code>inspect</code> string method. 
</p>

<pre class="explanation">
msg = "Jane\t17\nThomas\t23"
</pre>

<p>
This is a string with some special characters. 
</p>

<pre class="explanation">
puts msg
puts msg.inspect
</pre>

<p>
In the first case, the special characters are interpreted. There
is a tab and a newline between string parts. In the second case, we
get the string in a raw format. 
</p>

<pre>
$ ./inspectmethod.rb
Jane    17
Thomas  23
"Jane\t17\nThomas\t23"
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
The <code>chomp</code> method returns a new string with the record separator
removed from the end of the string. The default separator is the
newline (\n). 
</p>

<pre class="code">
#!/usr/bin/ruby

print "Are you sure to download? (Yes/No) "

response = gets

if (response.downcase == "yes")
    puts "Downloaded"
else
    puts "Download cancelled"
end

puts response.inspect
</pre>

<p>
In the above script, we get an input from the user. 
We react to the user response. 
</p>

<pre>
$ ./chomp.rb
Are you sure to download? (Yes/No) Yes
Download cancelled
"Yes\n"
</pre>

<p>
The script does not work correctly. The reason is clear, when we
look what returns the <code>inspect</code> method. The input from the
user is ended with an enter key. The newline character is included
in the response variable too. And "yes" does not equal to "yes\n". 
To correct the script, we use the <code>chomp</code> method. It removes
the newline from the variable. 
</p>

<pre class="code">
#!/usr/bin/ruby

print "Are you sure to download? (Yes/No) "

response = gets

if (response.downcase.chomp == "yes")
    puts "Downloaded"
else
    puts "Download cancelled"
end

puts response.inspect
</pre>

<p>
This is the corrected example. 
</p>

<pre class="explanation">
if (response.downcase.chomp == "yes")
</pre>

<p>
Here we process the input, before it is compared
with the "yes" string. The <code>chomp</code> method
removes the newline character.
</p>

<pre>
$ ./chomp.rb
Are you sure to download? (Yes/No) Yes
Downloaded
"Yes\n"
</pre>

<p>
Now the example works correctly. 
</p>


<h2>Formatting strings</h2>

<p>
Ruby has <b>format specifiers</b>. A format specifier determines how
the string is going to look like. It begins with a % character. Format
specifiers are put inside single or double quotes.
</p>

<p>
The format specifier has the following fields:
</p>

<pre>
%[flags][field width][precision]conversion specifier
</pre>

<p>
Fields in square brackets are optional. 
</p>

<p>
A <b>conversion specifier</b> specifies how the data is going to be converted into
displayable form. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "There are %d oranges in the basket." % 12
puts "There are %d oranges and %d apples in the basket." % [12, 10]
</pre>

<p>
Here is an example of some format specifiers. 
</p>

<pre class="explanation">
puts "There are %d oranges in the basket" % 12
</pre>

<p>
When we use the %d notation inside a string, we expect a number at 
that point. The d is a conversion specifier for decimal numbers. 
The number is given after the % character. 
</p>

<pre class="explanation">
puts "There are %d oranges and %d apples in the basket" % [12, 10]
</pre>

<p>
We can use multiple format specifiers inside a string. Each begins with
a % character. Multiple values are placed between [] characters and separated
by comma character. 
</p>

<pre>
$ ./formatspecifiers.rb
There are 12 oranges in the basket.
There are 12 oranges and 10 apples in the basket.
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
In the following example, we will cover some basic conversion specifiers.
</p>

<pre class="code">
#!/usr/bin/ruby

puts "There are %d apples." % 5
puts "I can see %i oranges." % 3
puts "The width of iPhone 3G is %f mm." % 62.1
puts "This animal is called a %s" % "rhinoceros."
</pre>

<p>
We have conversion specifiers for integers, floating point numbers
and strings. 
</p>

<pre class="explanation">
puts "There are %d apples." % 5
puts "I can see %i oranges." % 3
</pre>

<p>
Both d an i can be used for integers. 
</p>

<pre class="explanation">
puts "The width of iPhone 3G is %f mm." % 62.1
</pre>

<p>
The f is a conversion specifier for floating point values.
By default, floats have six decimal places.
</p>

<pre class="explanation">
puts "This animal is called a %s" % "rhinoceros."
</pre>

<p>
The s character is used for strings. 
</p>

<pre>
$ ./basicspecifiers.rb
There are 5 apples.
I can see 3 oranges.
The width of iPhone 3G is 62.100000 mm.
This animal is called a rhinoceros.
</pre>

<p>
Output of the example. 
</p>


<hr class="btm">

<p>
Next we have a practical example of using a format
specifier. 
</p>

<pre class="code">
#!/usr/bin/ruby

website = "zetcode.com"

website.each_char do |c|
    print "#{c} has ASCII code %d\n" % c.ord    
end
</pre>

<p>
In this example, we go through all characters of a 
string and print their ASCII values to the terminal. 
</p>


<pre class="explanation">
website.each_char do |c|
    print "#{c} has ASCII code %d\n" % c.ord    
end
</pre>

<p>
The <code>each_char</code> method passes each character
of a website string to the block. One character per cycle, with
current character stored in c variable. We get the ASCII code
of the character using the <code>ord</code> method, which returns
the ordinal of a one character string. 
</p>

<pre>
$ ./character.rb
z has ASCII code 122
e has ASCII code 101
t has ASCII code 116
c has ASCII code 99
o has ASCII code 111
d has ASCII code 100
e has ASCII code 101
. has ASCII code 46
c has ASCII code 99
o has ASCII code 111
m has ASCII code 109
</pre>

<p>
Output of the example.
</p>

<hr class="btm">

<p>
Numbers can be displayed in various forms. The conversion specifier 
can be used to format numbers.
</p>

<pre class="code">
#!/usr/bin/ruby

# decimal
puts "%d" % 300

# hexadecimal
puts "%x" % 300

# octal
puts "%o" % 300

# binary
puts "%b" % 300

# scientific
puts "%e" % (5/3.0)
</pre>

<p>
In the above example, we print numbers in decimal, hexadecimal, octal, binary and
scientific formats. 
</p>

<pre class="explanation">
# hexadecimal
puts "%x" % 300
</pre>

<p>
The x conversion specifier is used to transform a number into a hexadecimal format. 
</p>

<pre class="explanation">
# binary
puts "%b" % 300
</pre>

<p>
The x conversion specifier is used to transform a number into a binary format. 
</p>

<pre>
$ ./various.rb
300
12c
454
100101100
1.666667e+00
</pre>

<p>
Output. 
</p>

<hr class="btm">

<p>
<b>Precision</b> is a field in the format specifier. It is specified as a
number following a decimal point. It has a different
meaning for an integer, a floating point number and for a string. 
When used with integers, it indicates the minimum number of digits to
be printed. If the number has fewer digits than the precision, zeros
are prefixed. The default precision for integers is 1. Which means
that no zeros are filled. When used with a float number, the precision is
the number of digits displayed after the decimal point. Finally, with strings,
the precision is the maximum number of characters printed. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts 'Height: %f %s' % [172.3, 'cm']
puts 'Height: %.1f %s' % [172.3, 'cm']

puts "%d" % 16
puts "%.5d" % 16

puts "%s" % "zetcode"
puts "%.5s" % "zetcode"
</pre>

<p>
In this example, we will work with the precision field. 
</p>

<pre class="explanation">
puts 'Height: %f %s' % [172.3, 'cm']
puts 'Height: %.1f %s' % [172.3, 'cm']
</pre>

<p>
172.3 is a floating point number. If no precision is specified,
there will be 6 decimal places after a decimal point. In our case,
there will be 5 zeros. The .1 in the second code line is the precision.
For a floating point value, it reduces the number of decimal places to 1. 
</p>

<pre class="explanation">
puts "%d" % 16
puts "%.5d" % 16
</pre>

<p>
The default precision for integers is 1. In the second line, we have
specified precision .5, which adds (prepends) 3 zeros to the 16 number. 
</p>

<pre class="explanation">
puts "%s" % "zetcode"
puts "%.5s" % "zetcode"
</pre>

<p>
The first line prints all characters of the string. The second line
only five of them. Two characters are dropped. 
</p>

<pre>
$ ./precision.rb
Height: 172.300000 cm
Height: 172.3 cm
16
00016
zetcode
zetco
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
The <b>field width</b> specifies the minimum width of the data to be displayed.
It is a number, which comes before the decimal point, if it is present. 
If the output is shorter, then it is padded with spaces and it is right aligned. 
If we put a minus sign before the field width, it is left aligned.
If the output is longer than the field width, it is displayed in full. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "%d" % 1
puts "%d" % 16
puts "%d" % 165
puts "%d" % 1656
puts "%d" % 16567

puts "%10d" % 1
puts "%10d" % 16
puts "%10d" % 165
puts "%10d" % 1656
puts "%10d" % 16567
</pre>

<p>
In the first case, we print five numbers without specifying the field width.
The width of the output is equal to the number of the characters being displayed.
In the second case we have a field width of 10. Each of the 5 outputs has a minimum
length of 10 characters. The numbers are right aligned.
</p>

<pre class="explanation">
puts "%d" % 1
puts "%d" % 16
</pre>

<p>
We print two numbers. The width of the output has 1, 2 characters, respectively.
</p>

<pre class="explanation">
puts "%10d" % 1
puts "%10d" % 16
</pre>

<p>
Here the length in both cases is 10 characters. The two numbers are padded with
9, 8 spaces in the given order.
</p>

<pre>
$ ./fieldwidth.rb
1
16
165
1656
16567
         1
        16
       165
      1656
     16567
</pre>

<p>
We can see, that in the second case the numbers are right
aligned. 
</p>


<hr class="btm">

<p>
The <b>flag</b> modifies the behaviour of
the format. 
</p>

<p>
The # flag adds a prefix to binary, octal and hexadecimal
formats. 0b for binary, 0 for octal and 0x for hexadecimal.
It adds a decimal point to the floating point values,
event if the number of decimal places have been restricted by
the precision.
</p>

<pre class="code">
#!/usr/bin/ruby

puts "%#b" % 231
puts "%#x" % 231
puts "%#o" % 231

puts "%.0e" % 231
puts "%#.0e" % 231

puts "%.0f" % 231
puts "%#.0f" % 231
</pre>

<p>
In the code example, we use the x flag. 
</p>

<pre class="explanation">
puts "%#b" % 231
puts "%#x" % 231
puts "%#o" % 231
</pre>

<p>
The decimal 231 is printed in binary, octal, and hexadecimal formats.
The # flags adds a prefix for them. 
</p>

<pre class="explanation">
puts "%.0e" % 231
puts "%#.0e" % 231
</pre>

<p>
Here, the .0 precision supresses the decimal places of a number.
However, when used with a # flag, the decimal point is displayed. 
Despite the fact, that there are no decimal digits. 
</p>

<pre>
$ ./flags1.rb
0xe7
0b11100111
0347
2e+02
2.e+02
231
231.
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
The + flag adds a plus sign for positive decimal numbers.
For binary, octal and hexadecimal negative numbers it adds a minus sign 
and uses an absolute value.
</p>

<pre class="code">
#!/usr/bin/ruby

puts "%d" % 231
puts "%+d" % 231
puts "%d" % -231
puts "%+d" % -231

puts "%b" % -231
puts "%o" % -231
puts "%x" % -231

puts "%+b" % -231
puts "%+o" % -231
puts "%+x" % -231
</pre>

<p>
An example demonstrating the + flag of the format
specifier. 
</p>

<pre class="explanation">
puts "%d" % 231
puts "%+d" % 231
</pre>

<p>
Usually, positive numbers have their sign omitted. If we want to show
a plus sign for positive numbers, we specify the + flag. 
</p>

<pre class="explanation">
puts "%d" % -231
puts "%+d" % -231
</pre>

<p>
The + flag has no effect on negative numbers. The output is the same.
</p>

<pre class="explanation">
puts "%b" % -231
puts "%o" % -231
puts "%x" % -231
</pre>

<p>
Binary, octal and hexadecimal numbers have their own way to create
negative numbers. 
</p>

<pre class="explanation">
puts "%+b" % -231
puts "%+o" % -231
puts "%+x" % -231
</pre>

<p>
If we specify the + flag for these negative numbers, we transform a number
to a different format and add a minus sign. No special way of representing
negative numbers. 
</p>

<pre>
$ ./flags2.rb
231
+231
-231
-231
..100011001
..7431
..f19
-11100111
-347
-e7
</pre>

<p>
Output of the example.
</p>

<hr class="btm">

<p>
Here we introduce the 0 flag and the - flag. 
The 0 flag causes the number to be padded with zeros, instead of 
spaces. The - flag makes the output left aligned.
</p>

<pre class="code">
#!/usr/bin/ruby

puts "%010d" % 1
puts "%010d" % 16
puts "%010d" % 165
puts "%010d" % 1656
puts "%010d" % 16567

puts "%-10d" % 1
puts "%-10d" % 16
puts "%-10d" % 165
puts "%-10d" % 1656
puts "%-10d" % 16567
</pre>

<p>
Example.
</p>

<pre class="explanation">
puts "%010d" % 1
puts "%010d" % 16
</pre>

<p>
Numbers will be padded with zeros. 
</p>

<pre class="explanation">
puts "%-10d" % 1
puts "%-10d" % 16
</pre>

<p>
The number is shorter, than the field width. So it is aligned. And
the - flag makes it left aligned. 
</p>

<pre>
$ ./fieldwidth2.rb
0000000001
0000000016
0000000165
0000001656
0000016567
1         
16        
165       
1656      
16567
</pre>

<p>
Ouput of the example.
</p>


<hr class="btm">

<p>
The * flag can be used for the precision and for the width. Whenever we
use the * flag, we have to specify the precision or the width 
as an argument. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts "%.*f" % [3, 1.1111111]
puts "%0*d" % [10, 2]
puts "%0*.*f" % [10, 3, 1.1111]
</pre>

<p>
Example for the * flag. 
</p>

<pre class="explanation">
puts "%.*f" % [3, 1.1111111]
</pre>

<p>
Here we use the * flag for the precision. 
The first number, 3, is the argument for the precision.
It says only three decimal digits will be displayed for the
1.1111111 float number. 
</p>

<pre class="explanation">
puts "%0*d" % [10, 2]
</pre>

<p>
In this code line, we use the * flag for the width. We have to 
add the width between the [] brackets. The first number is the
width and the second number is the value for the conversion specifier.
</p>

<pre class="explanation">
puts "%0*.*f" % [10, 3, 1.1111]
</pre>

<p>
The * flag can be used for both the width and the precision. We have
to specify them both in the [] brackets. 
</p>

<pre>
$ ./flags3.rb
1.111
0000000002
000001.111
</pre>

<p>
Output of the example. 
</p>

<p>
This part of the Ruby tutorial covered strings. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 14, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

